import {renderVma} from './index'
import debounce from 'lodash/debounce'
import {vmaCom} from './com'

import styleinput from "../pageapp/styleinput";
import {objToStyle, sstyle} from "../pageapp/utils";

export default function (treeNode) {
  renderVma('propapp', [
    {
      components: {
        styleInput: styleinput({
          onLoad() {
          }
        })
      },
      data() {
        // console.log('desitem')
        let desitem = {}
        if (vvg.page.des[treeNode.name]) {
          desitem = vvg.page.des[treeNode.name]()
          if (treeNode.attributes && treeNode.attributes.sstyle) {
            let obj = JSON5.parse(treeNode.attributes.sstyle)
            for (let key in obj) {
              if (desitem && desitem[key]) {
                desitem[key].value = objToStyle(obj[key])
              }
            }
          }
        }
        return {
          desitem
        }
      },
      methods: {
        onStyleInput(e, desitem, desitemItemKey) {
          // this.testStyle = e
          console.log('onStyleInput')
          sstyle(treeNode, desitem, desitemItemKey, e)
          this.fireCom()
        },
        setDes(desKey, value) {
          this.des[desKey] = value
        }
      }
    },
    {
      data() {
        return {
          comname: treeNode.dataset.comType,
          model: {
            myObject: treeNode.attributes,
            myProp: {
              textContent: ''
            }
          },
          inited: false,
        }
      },
      methods: {
        fireCom() {
          document.dispatchEvent(new CustomEvent('com:change'))
        },
        onAttributeInput(v) {
          // console.log('onpropinput', v)
          this.onAttributeChange(v)
        },
        onAttributeChange: debounce(function (newVal) {
          treeNode.attributes = {
            ...newVal,
          }
          this.fireCom()
        }, 1000, {
          'leading': true,
          'trailing': false,
        }),
        onAttributeDelete(keyType) {
          // console.log(keyType)
          delete treeNode.attributes[keyType]
          this.$set(this.model, 'myObject', treeNode.attributes)
        },
        onPropInput(v) {
          console.log('onPropInput', v)
          this.onPropChange(v)
        },
        onPropChange: debounce(function (newVal) {
          treeNode.props = {
            ...newVal,
          }
          this.fireCom()
        }, 1000, {
          'leading': true,
          'trailing': false,
        }),
        onPropDelete(keyType) {
          // console.log(keyType)
          delete treeNode.props[keyType]
          this.$set(this.model, 'myProp', treeNode.props)
        },
      },
    },
    vmaCom,
  ])
}
